<?php
/**
 * Created by PhpStorm.
 * User: qufan
 * Date: 2016/12/6 0006
 * Time: 23:52
 */

namespace Home\Controller;


use Common\Logic\UserLogic;
use Think\Controller;

class HomeController extends Controller
{
    protected static $orgid,$orgids,$orgcode,$codes,$uids;

    protected function sucessJson($data = null){
        $result = array('status'=>1);
        empty($data) or $result['data'] = $data;
        $this->ajaxReturn($result);
    }

    protected function errorJson($msg, $data=null){
        $result = array('status'=>0, 'msg'=>$msg);
        empty($data) or $result['data'] = $data;
        $this->ajaxReturn($result);
    }

    /**
     * action访问控制,在 **登陆成功** 后执行的第一项权限检测任务
     *
     * @return boolean|null  返回值必须使用 `===` 进行判断
     *
     *   返回 **false**, 不允许任何人访问(超管除外)
     *   返回 **true**, 允许任何管理员访问,无需执行节点权限检测
     *   返回 **null**, 需要继续执行节点权限检测决定是否允许访问
     *
     */
    final protected function accessControl(){
        $allow = C('ALLOW_VISIT');
        $deny  = C('DENY_VISIT');
        $check = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);
        if ( !empty($deny)  && in_array_case($check,$deny) ) {
            return false;//非超管禁止访问deny中的方法
        }
        if ( !empty($allow) && in_array_case($check,$allow) ) {
            return true;
        }
        return null;//需要检测节点权限
    }

    protected function getUnreadMessageCount(){
        $where['receive_user_id'] = 0;
        $where['state'] = 1;
        $count = M('Message')->where($where)->count();
        $this->assign('unread_count', $count);
    }

    protected function _initialize(){
        if(defined('UID'))return;
        define('UID', is_login());
        if(!UID){
            $this->redirect('Public/login');
        }

        $user = session('user_auth');
        $this->assign("uid",   $user['uid']);
        $this->orgcode  = M('User')->where(array('user_id'=>$user['uid']))->getField('orgcode');
        $this->orgid    = M('User')->where(array('user_id'=>$user['uid']))->getField('org_id');
        $this->orgids   = array();

        if($user['uid']!=6){
            $parentcode = M('EmsOrg')->where(array('orgcode'=>$this->orgcode))->getField('parentcode');
            $Fs_code = $parentcode!=-1 ? array($parentcode, $this->orgcode) : array($this->orgcode);

            $data    = M('EmsOrg')->where(array('parentcode'=>$this->orgcode))->field('orgcode')->select();
            foreach($data as $_v){
                $Fs_code[] = $_v['orgcode'];
            }
            $this->codes = $Fs_code;

            $u_data = M('User')->where(array('orgcode'=>array('in', $this->codes)))->field('user_id')->select();
            foreach($u_data as $_v){
                $uids[] = $_v['user_id'];
            }
            $this->uids = $uids;

            $this->orgids = explode(',', $this->orgGroup_pid($this->orgid).','.$this->orgGroup($this->orgid));
        }

        /**
         * TODO 是否需要添加载入数据库配置
         */
        define('IS_ROOT', UserLogic::is_administrator());

        //检测系统权限
        if(!IS_ROOT){
//            $access = $this->accessControl();
//            if ( false === $access ) {
//                $this->error('403:禁止访问');
//            }elseif(null === $access ){
//                //检测访问权限
////                $rule  = strtolower(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME);
////                if ( !$this->checkRule($rule,array('in','1,2')) ){
////                    $this->error('未授权访问!');
////                }else{
////                    // 检测分类及内容有关的各项动态权限
////                    $dynamic    =   $this->checkDynamic();
////                    if( false === $dynamic ){
////                        $this->error('未授权访问!');
////                    }
////                }
//            }
        }
        $this->assign('__MENU__', $this->getMenus());
        $this->getUnreadMessageCount();
    }

    final public function getMenus(){
        $role_id = get_role_id();
        if($role_id == 0){
            return null;
        }
        $jurisdictions = UserLogic::getJurisdiction($role_id);
        if (false == $jurisdictions){
            return null;
        }
        array_unshift($jurisdictions, 0);
        $where['jurisdiction_id'] = array('in', $jurisdictions);
        $menus = null;
        if(empty($menus)){
            $menus = M('Menu')->where($where)->order('sort asc')->select();
            foreach ($menus as $key => $val){
                if(strtolower(CONTROLLER_NAME . '/' . ACTION_NAME) == strtolower($val['url'])){
                    $menus[$key]['class'] = 'active';
                }
            }
        }
        return $menus;
    }



    public function resetPassword(){
        $password_in = I('origin_pwd');
        $new_pwd = I('new_pwd');
        $repeat = I('repeat');
        if($new_pwd !== $repeat){
            $this->errorJson('两次输入的密码不一致');
        }
        $model = D('User');
        if($model->changePwd(UID, $password_in, $new_pwd)){
            $this->sucessJson();
        }else{
            $this->errorJson($model->getError());
        }
    }

    public function getOrgs(){
        if(!empty($this->orgids)){
            $orgs = M('Organizations')->where(array('org_id'=>array('in', $this->orgids)))->select();
        }else{
            $orgs = M('Organizations')->select();
        }
        array_unshift($orgs,array(
            'org_id' => 0,
            'org_name' => '所有',
            'parent_id'=>-1
        ));

        $tree = list_to_tree($orgs,'org_id', 'parent_id', 'nodes', -1, 'org_name');
        if($tree){
            $this->sucessJson($tree);
        }else{
            $this->errorJson('获取组织关系失败');
        }
    }
    /** 
    *add ：获取通讯分组树
    *user：边个懂
    *time：20170510
    **/
    public function getMail(){
        if(!empty($this->uids)){
            $where['_string'] = "group_code in(".implode(',', $this->codes).")";
        }
        $group_result = M('Mail_list_group')->where($where)->select();
        $tree = list_to_tree($group_result,'group_code', 'parent_code', 'nodes', -1, 'group_name');
        if($tree){
            $this->sucessJson($tree);
        }else{
            $this->errorJson('获取通讯分组失败');
        }
    }
    /**
    *add : 连接mail_list_group表获取group_name字段 获取role_name字段
    *add : 树形结构查询
    *add : $platform_status 参数 用于做选项分类
    *add : 添加删除后不显示，状态为3不显示
    *user：边个懂
    *time：20170510
     */
    public function userList($limit, $offset, $org_id = 0, $platform_status = 1, $search = null){
        if (!empty($org_id)) {
            if($org_id<$this->orgid) $org_id = $this->orgid;

            $temp = $this->orgGroup($org_id);
            !empty($temp) ? $map['u.org_id'] = array('in',$org_id.','.$temp) : $map['u.org_id'] = $org_id;
            // $map['u.org_id'] = $org_id;
        }
        // empty($role_id) or $map['u.role_id'] = $role_id;
        empty($platform_status) or $map['r.platform'] = $platform_status;
        // $platform_status == 1 && !empty($platform_status) ?  $map['r.platform'] = $platform_status : $map['u.role_id'] = $platform_status;
        empty($search) or $map['u.real_name'] = array('like', "%{$search}%");
        $map['u.state'] =array('neq',3);
        $field = 'u.user_id, u.sex, u.org_id, u.role_id, u.user_name, u.real_name,u.position, u.phone, u.IMEI, u.icon, u.state, u.password, u.IDCard, o.org_name,r.platform,r.role_name,m.group_name,m.group_code ';
        $record = M('User')->alias('u')->join('organizations o on u.org_id=o.org_id', 'left')->join('role r on u.role_id=r.role_id', 'left')->join('mail_list_group m on u.group_code=m.group_code','left')->where($map)->field($field)->limit($offset, $limit)->select();
        $total_count = M('User')->alias('u')->join('role r on u.role_id=r.role_id', 'left')->where($map)->count();
        $result['rows'] = $record;
        $result['total'] = $total_count;
        $this->ajaxReturn($result);
    }
    /**
    *add : 该方法用于Organizations表的分组递归
    *user：边个懂
    *time：20170510
     */
    public function orgGroup($parent_id,&$result=array()){
         $re = M('Organizations')->where("parent_id = ".$parent_id)->select();

         for ($i=0; $i < count($re); $i++) { 
            $result[]= $re[$i]['org_id'];
            $this->orgGroup($re[$i]['org_id'],$result);
         }
         return implode(',',$result);
    }

    public function orgGroup_pid($org_id=0,&$result=array()){
        $result[] = $org_id;
        $pid = M('Organizations')->where(array('org_id'=>$org_id))->getField('parent_id');
        if( $pid>0 ){
            $this->orgGroup_pid($pid,$result);
        }

        return implode(',',$result);
    }

}